package com.up.upzl.biz.controller;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.up.upzl.base.config.WeixinUtil;
import com.up.upzl.biz.domain.Captcha;
import com.up.upzl.biz.repository.CaptchaRepository;
import com.up.upzl.biz.service.paiDianRecordRepositorys;

@Controller
@RequestMapping("/isbinding")
public class WXbinding {

	@Autowired
	private paiDianRecordRepositorys paiDianRecordRepositorys;

	@Autowired
	private CaptchaRepository captchaRepository;

	private final Logger log = LoggerFactory.getLogger(getClass());
	String appid = "wxd3730802694fecf4";
	String appsecret = "f3e346607af09a2773c7b716865134b3";

	/**
	 * 验证是否已经绑定微信id
	 * 
	 * @throws Exception
	 */
	@RequestMapping("wx")
	public void wx(HttpServletResponse response) throws Exception {
		String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";

		log.info("授权地址模板:{}", authUrl);
		// 微信appid

		// 微信网页授权地址，这个是回调地址，回调地址必须在授权地址的下级
		// http://h5.zpb.youpuchina.com
		String callbackUrl = "http://h5.zpb.youpuchina.com/isbinding/openid";
		System.out.println("回调地址:" + callbackUrl);

		authUrl = authUrl.replace("APPID", appid);
		authUrl = authUrl.replace("REDIRECT_URI", URLEncoder.encode(callbackUrl, "UTF-8"));
		authUrl = authUrl.replace("SCOPE", "snsapi_base");

		System.out.println("真实授权地址:" + authUrl);

		response.sendRedirect(authUrl);
	}

	@RequestMapping("openid")
	public String openid(HttpServletRequest request, HttpServletResponse response, HttpSession session)
			throws Exception {
		System.out.println("收到回调请求");

		String code = request.getParameter("code");
		String state = request.getParameter("state");

		System.out.println("授权码:" + code);
		System.out.println("state:" + state);
		// 微信的appsecret秘钥

		// 通过code获取
		String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

		accessTokenUrl = accessTokenUrl.replace("APPID", appid);
		accessTokenUrl = accessTokenUrl.replace("SECRET", appsecret);
		accessTokenUrl = accessTokenUrl.replace("CODE", code);

		System.out.println("通过code换取用户openid地址:" + accessTokenUrl);

		String result = WeixinUtil.httpRequest(accessTokenUrl, "GET", null);
		System.out.println("获取用户openid结果:" + result);

		String openid = JSONObject.parseObject(result).getString("openid");
		session.setAttribute("openid", openid);

		System.out.println("===>openid:" + openid);

		List<Captcha> binding = new ArrayList<>();
		binding = captchaRepository.findByOpenid(openid);
		try {
			Captcha BI = binding.get(0);
			String phone = BI.getPhone();
			session.setAttribute("phone", phone);
		} catch (Exception e) {
			log.info("用户未授权");
		}
		if (!binding.isEmpty()) {
			return "/assignment.html";
		} else {
			log.info("用户未授权，跳转都登录页页面");
			return "/login.html";
		}

	}

}
